package com.dacd.android.multi.scan.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.dacd.android.multi.scan.R;
import com.dacd.android.multi.scan.bean.ScanResultBean;
import com.dacd.android.multi.scan.handler.MainActivityHandler;
import com.dacd.android.multi.scan.qrtools.BeepManager;
import com.dacd.android.multi.scan.qrtools.DecodeFormatManager;
import com.dacd.android.multi.scan.qrtools.DecodeHintManager;
import com.dacd.android.multi.scan.qrtools.InactivityTimer;
import com.dacd.android.multi.scan.qrtools.IntentSource;
import com.dacd.android.multi.scan.qrtools.Intents;
import com.dacd.android.multi.scan.qrtools.ViewfinderView;
import com.dacd.android.multi.scan.qrtools.camera.CameraManager;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import static android.R.attr.action;

public class MainActivity extends Activity implements SurfaceHolder.Callback {

    private enum ResultState {
        THREE_OK,
        TWO_OK,
        NONE
    }

    private InactivityTimer inactivityTimer;//低电量关闭摄像头
    private BeepManager beepManager;//扫描声音
    private CameraManager cameraManager;//摄像头
    private ViewfinderView viewfinderView;//显示区域
    private IntentSource source;
    private String sourceUrl;
    private Collection<BarcodeFormat> decodeFormats;
    private Map<DecodeHintType, ?> decodeHints;
    private String characterSet;
    private MainActivityHandler mainActivityHandler;
    private boolean hasSurface;
    private ResultState resultState;
    private TextView twoOkTv, threeOkTv;
    private ScanResultBean scanResultBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//屏幕保持常亮
        setContentView(R.layout.activity_main);
        twoOkTv = (TextView) findViewById(R.id.two_ok_tv);
        threeOkTv = (TextView) findViewById(R.id.three_ok_tv);
        resultState = ResultState.NONE;
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        scanResultBean = new ScanResultBean();
    }

    @Override
    protected void onResume() {
        super.onResume();
        cameraManager = new CameraManager(getApplication());
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        viewfinderView.setCameraManager(cameraManager);
        viewfinderView.setVisibility(View.VISIBLE);
        inactivityTimer.onResume();
        Intent intent = getIntent();
        source = IntentSource.NONE;
        decodeFormats = null;
        characterSet = null;
        if (intent != null) {
            if (Intents.Scan.ACTION.equals(action)) {
                source = IntentSource.NATIVE_APP_INTENT;
                decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
                decodeHints = DecodeHintManager.parseDecodeHints(intent);
                if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
                    int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
                    int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
                    if (width > 0 && height > 0) {
                        cameraManager.setManualFramingRect(width, height);
                    }
                }

                if (intent.hasExtra(Intents.Scan.CAMERA_ID)) {
                    int cameraId = intent.getIntExtra(Intents.Scan.CAMERA_ID, -1);
                    if (cameraId >= 0) {
                        cameraManager.setManualCameraId(cameraId);
                    }
                }
            }
            characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
        }
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            // Install the callback and wait for surfaceCreated() to init the camera.
            surfaceHolder.addCallback(this);
        }
    }


    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a RuntimeException.
            if (mainActivityHandler == null) {
                mainActivityHandler = new MainActivityHandler(this, decodeFormats, decodeHints, characterSet, cameraManager);
            }
        } catch (IOException ioe) {
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.?lang.?RuntimeException: Fail to connect to camera service
        }
    }

    public void handleDecode(Result[] rawResult, Bitmap barcode, float scaleFactor) {
        if (rawResult.length == 3) {//扫中2个二维码
            if (rawResult[2].getText().startsWith("2/") && rawResult[2].getText().split("/").length == 6) {//扫中了正确的数据
                if (resultState == ResultState.TWO_OK) {
                    mainActivityHandler.sendEmptyMessageDelayed(R.id.restart_preview, 100L);
                    return;
                }
                twoOkTv.setText("2--OK");
                scanResultBean.setMsg2_1(rawResult[0].getText());
                scanResultBean.setMsg2_2(rawResult[1].getText());
                if (resultState == ResultState.NONE) {
                    resultState = ResultState.TWO_OK;
                    mainActivityHandler.sendEmptyMessageDelayed(R.id.restart_preview, 100L);
                } else if (resultState == ResultState.THREE_OK) {//3和2都扫描OK了
                    jumpToResult();
                }
            } else {
                mainActivityHandler.sendEmptyMessageDelayed(R.id.restart_preview, 100L);
            }
        } else if (rawResult.length == 4) {//扫中3个二维码
            if (rawResult[3].getText().startsWith("2/") && rawResult[3].getText().split("/").length == 19) {//扫中目标二维码
                if (resultState == ResultState.THREE_OK) {
                    mainActivityHandler.sendEmptyMessageDelayed(R.id.restart_preview, 100L);
                    return;
                }
                threeOkTv.setText("3--OK");
                scanResultBean.setMsg3_1(rawResult[0].getText());
                scanResultBean.setMsg3_2(rawResult[1].getText());
                scanResultBean.setMsg3_3(rawResult[2].getText());
                if (resultState == ResultState.NONE) {
                    resultState = ResultState.THREE_OK;
                    mainActivityHandler.sendEmptyMessageDelayed(R.id.restart_preview, 100L);
                } else if (resultState == ResultState.TWO_OK) {//3和2都扫描OK了
                    jumpToResult();
                }
            }
        } else {
            mainActivityHandler.sendEmptyMessageDelayed(R.id.restart_preview, 100L);
        }
    }

    /**
     * 跳转到结果界面
     */
    private void jumpToResult() {
        Intent intent = new Intent(MainActivity.this, ResultActivity.class);
        intent.putExtra("resultBean", scanResultBean);
        startActivity(intent);
        resetScreen();
    }

    /**
     * 重新设置界面
     */
    private void resetScreen() {
        twoOkTv.setText("");
        threeOkTv.setText("");
        resultState = ResultState.NONE;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    protected void onPause() {
        if (mainActivityHandler != null) {
            mainActivityHandler.quitSynchronously();
            mainActivityHandler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();
        //historyManager = null; // Keep for onActivityResult
        if (!hasSurface) {
            SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            surfaceHolder.removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    public Handler getHandler() {
        return mainActivityHandler;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
//                if (source == IntentSource.NATIVE_APP_INTENT) {
//                    setResult(RESULT_CANCELED);
//                    finish();
//                    return true;
//                }
                if ((source == IntentSource.NONE || source == IntentSource.ZXING_LINK)) {
                    mainActivityHandler.sendEmptyMessageDelayed(R.id.restart_preview, 0L);
                    return true;
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * @param filePath 传入的文件路径
     * @return
     */
    private String getLastWord(String filePath) {
        if (filePath.contains("/")) {
            return filePath.substring(filePath.lastIndexOf("/") + 1);
        }
        return filePath;
    }
}
